package com.zcn.io.web.auth;

import com.zcn.io.common.exception.ServiceException;
import com.zcn.io.web.api.entity.SysRole;
import com.zcn.io.web.api.entity.User;
import com.zcn.io.web.service.CacheService;
import com.zcn.io.web.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: 202438 邱建伟
 * @date: 2024/10/13 16:51
 * @Copyright (c) 2024, 江苏金恒信息科技股份有限公司
 */
@AllArgsConstructor
@Component
public class UserLoginService implements UserDetailsService {

    private final UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getByAccountNo(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        //查询对应的权限信息
        List<SysRole> rolesByUserId = userService.getRolesByUserId(user.getId());
        List<String> permissions = rolesByUserId.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        return new LoginUser(user, permissions);
    }
}
